package jdbc;

import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * 使用JDBCUtils完成数据库相关操作
 */
public class JDBCUtilsUse {

    public static void main(String[] args) {

    }

    @Test
    public void testDML() {
        //1.得到连接
        Connection connection = null;
        //2.组织sql语句
        String sql = "update actor set name = ? where id = ?";
        //3.创建PreparedStatement对象
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            // 给占位符赋值
            preparedStatement.setString(1, "周星驰");
            preparedStatement.setInt(2, 2);
            //执行
            int rows = preparedStatement.executeUpdate();
            System.out.println(rows > 0?"成功":"失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

    @Test
    public void testSelect() {
        //1.得到连接
        Connection connection = null;
        //2.组织sql语句
        String sql = "select * from actor where id = ?";
        //3.创建PreparedStatement对象
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 2);
            //执行查询语句，得到返回值resultSet
            resultSet = preparedStatement.executeQuery();
            //循环取数据
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date date = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex + "\t" + date + "\t" + phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            JDBCUtils.close(resultSet, preparedStatement, connection);
        }
    }
}
